<template>
  <div class="page-container">
    <!-- 显示选中成员 -->
    <div class="selected-members-container">
      <div class="member-list-title">已选成员 ({{ members.length }})</div>
      <div class="member-list">
        <div v-for="member in members" :key="member.id" class="member-item">
          {{ member.label }}
        </div>
      </div>
    </div>

    <!-- 添加触发按钮 -->
    <van-button type="primary" @click="showPopup = true" class="show-org-btn">
      显示组织架构
    </van-button>

    <!-- 上拉菜单包裹Org组件 -->
    <van-popup
      v-model="showPopup"
      position="bottom"
      :style="{ height: '90vh' }"
      round
    >
      <div class="popup-content" v-if="showPopup">
        <Org
          :tree-data="orginTreeData"
          @change="handleTreeChange"
          @confirm="handleConfirm"
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Org from "@/components/Org";

export default {
  components: {
    Org,
  },
  name: "Home",
  data() {
    return {
      showPopup: false,
      apiTreeData: [],
      members: [],
    };
  },
  computed: {
    ...mapState({
      orginTreeData: (state) => state.orgTree.orginTreeData,
    }),
  },
  watch: {
    orginTreeData: {
      deep: true,
      handler(newVal) {
        // console.log("【Home】树数据变化:", newVal);
      },
    },
  },
  created() {
    // 使用示例
    const mockTreeData = this.generateOrgTree();
    const treeData = this.initTree(mockTreeData);
    const flatTreeData = this.flattenTree(treeData);

    // console.log(treeData);
    // console.log(JSON.stringify(treeData, null, 2));
    console.log("扁平化树结构：", flatTreeData);

    this.$store.dispatch("orgTree/setOrgTreeData", treeData);
    this.$store.dispatch("orgTree/setFlatTreeData", flatTreeData);
    this.$store.dispatch("orgTree/setNodes", []);
  },
  methods: {
    /**
     * 生成混合部门/成员的树形数据
     * @param {number} depth 当前深度（1-5）
     * @param {number} parentId 父节点ID
     * @returns {Array} 生成的树形数据
     */
    generateOrgTree(depth = 1, parentId = 0) {
      // 每层生成5-10个节点
      const nodeCount = Math.floor(Math.random() * 6) + 5;
      const result = [];
      let idCounter = parentId * 100 || 1;

      for (let i = 0; i < nodeCount; i++) {
        const nodeId = idCounter + i;
        // 随机决定当前节点是部门还是成员（深度<5时部门概率更高）
        const isDepartment = depth < 5 ? Math.random() > 0.4 : false;

        const node = {
          id: nodeId,
          label: this.generateLabel(depth, i, isDepartment),
          type: isDepartment ? "department" : "person",
        };

        // 如果是部门且未达最大深度，生成子节点
        if (isDepartment && depth < 5) {
          node.children = this.generateOrgTree(depth + 1, nodeId);
        }

        result.push(node);
      }

      return result;
    },

    /**
     * 生成节点标签（区分部门和成员）
     */
    generateLabel(depth, index, isDepartment) {
      const depTypes = ["研发部", "市场部", "运维部", "测试部", "设计部"];
      const personNames = [
        "张",
        "王",
        "李",
        "赵",
        "刘",
        "陈",
        "杨",
        "黄",
        "周",
        "吴",
      ];
      const secondNames = [
        "明",
        "伟",
        "芳",
        "娜",
        "强",
        "杰",
        "敏",
        "静",
        "磊",
        "洋",
      ];
      const teamNames = ["前端组", "后端组", "算法组", "产品组", "测试组"];
      const positions = ["工程师", "经理", "总监", "助理", "专员"];

      // 使用静态变量记录已用名字
      if (!this.usedNames) {
        this.usedNames = new Set();
      }

      if (depth === 1) {
        return ["集团总部", "产品中心", "技术中心", "运营中心", "财务中心"][
          index % 5
        ];
      }

      if (isDepartment) {
        if (depth === 2) return `${teamNames[index % 5]}`;
        return `${depTypes[index % 5]}${depth}级`;
      } else {
        // 生成不重复的人名
        let fullName;
        let attempt = 0;
        do {
          const firstName = personNames[(index + attempt) % personNames.length];
          const secondName =
            secondNames[(depth + attempt) % secondNames.length];
          fullName = firstName + secondName;
          attempt++;

          // 防止无限循环
          if (attempt > 100) {
            fullName = firstName + secondName + index;
            break;
          }
        } while (this.usedNames.has(fullName));

        this.usedNames.add(fullName);
        return `${fullName}·${positions[index % 5]}`;
      }
    },

    // 给树结构加层级level属性和选中状态checkedStatus属性
    initTree(data, level = 1, parentId = 0) {
      // 处理数组中的每个节点
      return data.map((item) => {
        // 给当前节点添加属性
        item.level = level;
        item.checkedStatus = "unchecked";
        item.parentId = parentId;

        // 如果有子节点，递归处理
        if (item.children && item.children.length) {
          item.children = this.initTree(item.children, level + 1, item.id);
        }

        return item;
      });
    },

    // 扁平化树结构
    flattenTree(treeData) {
      const result = [];
      const flatten = (nodes, level = 1, parentId = null) => {
        nodes.forEach((node) => {
          const flatNode = {
            ...node,
          };
          result.push(flatNode);
          if (node.children && node.children.length) {
            flatten(node.children, level + 1, node.id);
          }
        });
      };
      flatten(treeData);
      return result;
    },

    // 处理树形结构的点击事件
    handleTreeChange(data) {
      console.log("根节点监听到change事件：", data);
      this.$store.dispatch("orgTree/setOrgTreeData", data);
    },

    // 处理确认按钮的点击事件
    handleConfirm(data) {
      console.log("确认按钮点击事件：", data);
      this.members = [...data];
      this.showPopup = false;
    },
  },
};
</script>

<style scoped lang="less">
.page-container {
  padding: 20px;

  .show-org-btn {
    width: 120px;
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 1;
  }

  .popup-content {
    position: relative;
    height: 100%;
    padding: 0; /* 新增 */
    overflow: hidden; /* 只在最外层控制滚动 */
  }

  /* 调整Org组件内部样式 */
  .org-container {
    height: 100%; /* 修改 */
    padding-top: 0; /* 修改 */
  }

  .selected-members-container {
    margin-bottom: 16px;
    background: #f7f8fa;
    border-radius: 8px;
    padding: 12px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }

  .member-list-title {
    font-size: 14px;
    color: #969799;
    margin-bottom: 8px;
  }

  .member-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .member-item {
    background: #ffffff;
    border: 1px solid #ebedf0;
    border-radius: 16px;
    padding: 4px 12px;
    font-size: 13px;
    color: #323233;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }
}
</style>
